package conf

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
)

type AppConfig struct {
	*MysqlConfig `mapstructure:"mysql"`
	*Auth        `mapstructure:"auth"`
	*Listen      `mapstructure:"listen"`
}

type MysqlConfig struct {
	ADDRESS  string `mapstructure:"address"`
	USER     string `mapstructure:"user"`
	PASSWORD string `mapstructure:"password"`
	DBNAME   string `mapstructure:"dbname"`
}
type Auth struct {
	TOKEN string `mapstructure:"token"`
}

type Listen struct {
	Host string `mapstructure:"host"`
	Port string `mapstructure:"port"`
}

var Server = new(AppConfig)

func DBinit() {
	viper.SetConfigFile("conf/config.yaml")
	err := viper.ReadInConfig() // 读取配置信息
	if err != nil {

		// 读取配置信息失败
		fmt.Printf("viper Read Config failed, err:%v\n", err)
		return
	}

	// 把读取到的配置信息反序列化到 Conf 变量中
	if err := viper.Unmarshal(Server); err != nil {
		fmt.Printf("viper Unmarshal failed, err:%v\n", err)
	}

	viper.WatchConfig() // 对配置文件进行监视，若有改变就重新反序列到Conf中
	viper.OnConfigChange(func(in fsnotify.Event) {

		fmt.Println("配置文件修改了...")
		if err := viper.Unmarshal(Server); err != nil {
			fmt.Printf("viper.Unmarshal failed, err:%v\n", err)
		}
	})
	return
}
